package com.link.base.base.pageupload.utils;


import com.link.base.base.pageupload.model.Chunk;
import com.link.core.cllog.LCLogger;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.stream.Stream;

/** 
 * 大文件分片上传-文件处理帮助类
 * @author 许博文  
 * @date 2019/12/25
 */
public class FileUtils {

    /**
     * DESC: 生成路径
     *
     * @Auther: bowen.xu
     * @date: 2019-01-10 09:33
     * @param: [uploadFolder, chunk]
     * @return: java.lang.String
     */
    public static String generatePath(String uploadFolder, Chunk chunk) {
        StringBuilder sb = new StringBuilder();
        sb.append(uploadFolder).append("/").append(chunk.getIdentifier());
        //判断uploadFolder/identifier 路径是否存在，不存在则创建
        if (!Files.isWritable(Paths.get(sb.toString()))) {
//            log.info("path not exist,create path: {}", sb.toString());
            try {
                Files.createDirectories(Paths.get(sb.toString()));
            } catch (IOException e) {
                LCLogger.withException(e);
            }
        }

        return sb.append("/")
                .append(chunk.getFileName())
                .append("-")
                .append(chunk.getChunkNumber()).toString();
    }

    /**
     * DESC: 文件合并
     *
     * @Auther: bowen.xu
     * @date: 2019-01-10 09:33
     * @param: [targetFile, folder, filename]
     * @return: void
     */
    public static void merge(String targetFile, String folder, String filename) {
        Stream<Path> list = null;
        try {
            Files.createFile(Paths.get(targetFile));
            list = Files.list(Paths.get(folder));
            list.filter(path -> !path.getFileName().toString().equals(filename))
                    .sorted((o1, o2) -> {
                        String p1 = o1.getFileName().toString();
                        String p2 = o2.getFileName().toString();
                        int i1 = p1.lastIndexOf("-");
                        int i2 = p2.lastIndexOf("-");
                        return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
                    })
                    .forEach(path -> {
                        try {
                            //以追加的形式写入文件
                            Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND);
                            //合并后删除该块
                            Files.delete(path);
                        } catch (IOException e) {
                            LCLogger.withException(e);
                        }
                    });
        } catch (IOException e) {
            LCLogger.withException(e);
        } finally {
            if (list != null) {
                list.close();
            }
        }

    }
}
